--
-- Author: shunguo.chen
-- Date: 2018-01-09 15:24:29
--
-- CosplayView

local AvatarFactory = app:getClass("AvatarFactory")

local CosplayHeadRender = import(".renders.CosplayHeadRender")
local CosplayRender = import(".renders.CosplayRender")
local CosplayGroupRender = import(".renders.CosplayGroupRender")
local CosplayBigRender = import(".renders.CosplayBigRender")
local SkillSimpleRender = require("app.widget.renders.SkillSimpleRender")
local ListViewVertical = require("app.widget.listview.ListViewVertical")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ViewBase)

ClassRef.VIEW_ROOT_RES = Res.CosplayScene

local START_TIME_STR = L("lua_code_text_449")

local ROLE_MID_INDEX = 4

local timeout = 0
local timeTextOk
local timeTextDel
local tipsText

function ClassRef:init()
	self._ui.Button_close:setVisible(false)
	self._ui.Button_close:addClickEventListener(handler(self, self._onBtnClick))

	-- Panel_mid --
	local con = self._ui["Panel/Panel_mid"]
	self._roleCon = con:getChildByName("Node_position")
	self._selectTips = con:getChildByName("icon_tips")

	local dataPanel = con:getChildByName("Panel_data")
	self._nameText = dataPanel:getChildByName("name")
	self._classIcon = dataPanel:getChildByName("class_icon")
	self._classText = dataPanel:getChildByName("job")
	self._dataPanel = dataPanel
	local _, conHeight = con:getContentSize2()
	self._dataPanelMinPosY = dataPanel:getPositionY()
	self._dataPanelMaxPosY = conHeight

	-- head
	local headPanel = con:getChildByName("Panel_head")
	self._headPanel = headPanel
	self._roleRenders = {0,0,0,0,0,0,0}
	for i=1,7 do
		local render = CosplayHeadRender.create(headPanel:getChildByName("node_" .. i))
		render:onBtnClick(handler(self, self._onClickRender))
		render:setIndex(i)
		self._roleRenders[i] = render
	end

	self._leftBtn = con:getChildByName("Button_l")
	self._rightBtn = con:getChildByName("Button_r")
	self._leftBtn:addClickEventListener(handler(self, self._onBtnClick))
	self._rightBtn:addClickEventListener(handler(self, self._onBtnClick))

	-- con:getChildByName("Button_explain"):addClickEventListener(handler(self, self._onBtnClick))

	-- skill
	local skillPanel = con:getChildByName("Panel_skill")
	self._skillRenders = {0,0,0,0}
	for i=1,4 do
		local render = SkillSimpleRender.create(skillPanel:getChildByName("skill_" .. i))
		render:setTipEnable(true)
		self._skillRenders[i] = render
	end

	self._okBtn = skillPanel:getChildByName("Button_ok")
	self._okBtn:addClickEventListener(handler(self, self._onBtnClick))
	self._delBtn = skillPanel:getChildByName("Button_del")
	self._delBtn:addClickEventListener(handler(self, self._onBtnClick))
	timeTextOk = self._okBtn:getChildByName("time")
	timeTextDel = self._delBtn:getChildByName("time")

	tipsText = con:getChildByName("Text_tips")

    self._panelTips = self._ui["Panel/Panel_tips"]
    self._panelTips:setVisible(true)

end

function ClassRef:_initUIRenders()
	-- left/my  right/enemy
	local info = self._data[1]
	local tp = info:getType()
	if tp == Enums.CosplayType.pve then
		--竞速模式使用了该处内容 左侧目前使用的是Panel_5_l 但是遇到团队竞速本 则不适用 团队竞速本使用ScrollView
		self._ui.Panel_1_l:setVisible(false)
		self._ui.Panel_5_r:setVisible(false)
	elseif tp == Enums.CosplayType.pve10 then
		self._ui.Panel_1_l:setVisible(false)
		self._ui.Panel_5_r:setVisible(false)
		self._ui.Panel_5_l:setVisible(false)

		self._ui.ScrollView:setVisible(true)


		local params = {
			renderClass = CosplayGroupRender,
			perNum = 1,
			cellEventProxy = function(eventName, render)
				if render then
					dump("稍后处理。。可能也不处理")
				end
			end,
		}

		self._renderList = ListViewVertical.new(self._ui.ScrollView, params)

	elseif tp == Enums.CosplayType.pvp1 then
		self._ui.Panel_5_l:setVisible(false)
		self._ui.Panel_5_r:setVisible(false)
	elseif tp == Enums.CosplayType.pvp5 then
		self._ui.Panel_1_l:setVisible(false)
		self._ui.Panel_1_r:setVisible(false)
	end

	if self._ui.Panel_1_l:isVisible() then
		self._myRender = CosplayBigRender.create(self._ui.Panel_1_l)
	else
		self._ui.Panel_1_l:removeFromParent()
	end
	if self._ui.Panel_1_r:isVisible() then
		self._enemyRender = CosplayBigRender.create(self._ui.Panel_1_r)
	else
		self._ui.Panel_1_r:removeFromParent()
	end
	if self._ui.Panel_5_l:isVisible() then
		self._myRenders = {0,0,0,0,0}
		for i=1,5 do
			local render = CosplayRender.create(self._ui.Panel_5_l:getChildByName("p" .. i))
			self._myRenders[i] = render
		end
	else
		self._ui.Panel_5_l:removeFromParent()
	end
	if self._ui.Panel_5_r:isVisible() then
		self._enemyRenders = {0,0,0,0,0}
		for i=1,5 do
			local render = CosplayRender.create(self._ui.Panel_5_r:getChildByName("p" .. i))
			self._enemyRenders[i] = render
		end
	else
		self._ui.Panel_5_r:removeFromParent()
	end
end

function ClassRef:onExit()
	self.super.onExit(self)
	timeTextOk = nil
	timeTextDel = nil
	tipsText = nil
end

function ClassRef:show()
	self.super.show(self)
	self:refresh()
end

function ClassRef:_onBtnClick(sender)
	local name = sender:getName()
	if name == "Button_close" then
		executeFunc(self._onCloseView)
	elseif name == "Button_explain" then
		local role = self._curRender:getData()
		executeFunc(self._onOperate, "openBook", role)
	elseif name == "Button_l" then
		self:_refreshRoleRenders(self._curRoleIdx-1)
	elseif name == "Button_r" then
		self:_refreshRoleRenders(self._curRoleIdx+1)
	elseif name == "Button_ok" then
		local role = self._curRender:getData()
		executeFunc(self._onOperate, "selectRole", role.id)
	elseif name == "Button_del" then
		executeFunc(self._onOperate, "selectRole", 0)
	end
end

function ClassRef:_onClickRender(render)
	local index = render:getIndex()
	self:_refreshRoleRenders(self._curRoleIdx + index - ROLE_MID_INDEX)
end

function ClassRef:setCurRender(render)
	if self._curRender ~= render then
		if self._curRender then
			self._curRender:setSelected(false)
		end
		render:setSelected(true)
		self._curRender = render
	end

	self:_refreshRole(render:getData())
end

function ClassRef:_refreshRole(role)
	local avatarParams = role:getAvatarParams()

	self._nameText:setString(avatarParams.name)
	self._classIcon:loadTexture(GD:getClassIcon(avatarParams.classID, 2))
	self._classText:setString(role:getDuty())

    local roleDesc = self._panelTips:getChildByName("text")
    roleDesc:setString(role._roleSimpleDesc)

	self._selectTips:setVisible(role:isChoose() and not role:isMyChoose())
	--如果现在是pve10 则不显示
	local tp = self._myInfo:getType()
	if tp == Enums.CosplayType.pve10 then
		self._selectTips:setVisible(false)
	end


	if self._okBtn:isVisible() then
		if tp == Enums.CosplayType.pve10 then
			display.setBtnTouchEnable(self._okBtn, true)
		else
			display.setBtnTouchEnable(self._okBtn, not role:isChoose())
		end
	end

	-- avatar
	self._roleCon:removeAllChildren()
	AvatarFactory.preloadHero(avatarParams, function()
		if not tolua.isnull(self) then
			self._roleCon:removeAllChildren()
			local hero = AvatarFactory.createHero(avatarParams)
			self._roleCon:addChild(hero)
			hero:play("mapidle")
		end
	end)

	local skills = role:getSkills()
	for i,render in ipairs(self._skillRenders) do
		render:setData(skills[i])
	end
end

function ClassRef:_refreshRoleRenders(sIdx)
	local maxLen = #self._roles
	sIdx = sIdx or ROLE_MID_INDEX
	sIdx = math.checkIn(sIdx, 1, maxLen)

	local myInfo = self._myInfo
	local tp = myInfo:getType()
	
	for i,render in ipairs(self._roleRenders) do
		local idx = sIdx + i - ROLE_MID_INDEX
		idx = math.checkIn(idx, 1, maxLen)
		render:setData(self._roles[idx])
		render:setCurCosplayType(tp)
	end

	self._curRoleIdx = sIdx
	self:setCurRender(self._roleRenders[ROLE_MID_INDEX])
end

function ClassRef:_setHeadPanelVisible(b)
	local visible = self._headPanel:isVisible()
	if visible ~= b then
		self._headPanel:setVisible(b)
		self._leftBtn:setVisible(b)
		self._rightBtn:setVisible(b)

		self._dataPanel:setPositionY(b and self._dataPanelMinPosY or self._dataPanelMaxPosY)
	end
end

-- data = {CosplayInfo, ...}
-- roles = {CosplayRole, ...}
function ClassRef:setData(data, roles)
	local isFirst = self._data == nil
	self._data = data
	if isFirst then
		-- 第一次设置data，初始化ui
		self:_initUIRenders()
	end

	self._roles = roles
	self._myInfo = nil
	self._enemyInfo = nil
	for i,v in ipairs(self._data) do
		if v:isMyTeam() then
			self._myInfo = v
		else
			self._enemyInfo = v
		end
	end

	self._curRoleIdx = ROLE_MID_INDEX
end

-- info = CosplayInfo／nil 更新的一组（nil全更新）
function ClassRef:refresh(info)
	local myInfo = self._myInfo
	local enemyInfo = self._enemyInfo

	local tp = myInfo:getType()
	if tp == Enums.CosplayType.pve then
		self._enemyRender:setBossData(myInfo:getBossTarget())

		local choices = myInfo:getChoices()
		for i, render in ipairs(self._myRenders) do
			render:setData(choices[i])
		end
	elseif tp == Enums.CosplayType.pve10 then
		self._enemyRender:setBossData(myInfo:getBossTarget())

		local choices = myInfo:getChoices()
		table.sort(choices,function(a,b)
			return a:isMe()
		end)
		self._renderList:reloadData(choices)

	elseif tp == Enums.CosplayType.pvp1 then
		self._enemyRender:setIsEnemy(true)
		if info then
			local choices = info:getChoices()
			if info:isMyTeam() then
				self._myRender:setData(choices[1])
			else
				self._enemyRender:setData(choices[1])
			end
		else
			local choices = myInfo:getChoices()
			self._myRender:setData(choices[1])
			local choices = enemyInfo:getChoices()
			self._enemyRender:setData(choices[1])
		end
	elseif tp == Enums.CosplayType.pvp5 then
		if info then
			local choices = info:getChoices()
			if info:isMyTeam() then
				for i, render in ipairs(self._myRenders) do
					render:setData(choices[i])
				end
			else
				for i, render in ipairs(self._enemyRenders) do
					render:setData(choices[i])
				end
			end
		else
			local choices = myInfo:getChoices()
			for i, render in ipairs(self._myRenders) do
				render:setData(choices[i])
			end
			local choices = enemyInfo:getChoices()
			for i, render in ipairs(self._enemyRenders) do
				render:setData(choices[i])
			end
		end
	end

	-- 确定按钮／时间
	timeTextOk:stopAllActions()
	if not myInfo:isFinish() then
		tipsText:setVisible(false)

		local isMyselfChoosed = myInfo:hasMyselfChoosed()
		self:_setHeadPanelVisible(not isMyselfChoosed)
		self._okBtn:setVisible(not isMyselfChoosed)
		self._delBtn:setVisible(isMyselfChoosed)

		self:_refreshRoleRenders(self._curRoleIdx)
	else
		self._okBtn:setVisible(false)
		self._delBtn:setVisible(false)
		tipsText:setVisible(true)
		self:_setHeadPanelVisible(false)

		-- 刷新选择
		local myRole = myInfo:getMyChooseRole()
		local curRole = self._curRender and self._curRender:getData() or nil
		if myRole and myRole ~= curRole then
			self:_refreshRole(myRole)
		end
    end
	timeout = myInfo:getRestTime()
	self:_refreshTime()
end

function ClassRef:_refreshTime()
	local isFinish = self._myInfo:isFinish()
	if (timeout == 0 and isFinish) or timeout < 0 then
		-- 时间到，关闭界面
		print("CosplayView auto close")
    	executeFunc(self._onCloseView)
    	return
	end

	if isFinish then
    	-- 选人结束后，5秒进入场景
    	tipsText:setString(string.format(START_TIME_STR, timeout))
	else
		if self._okBtn:isVisible() then
			timeTextOk:setString(string.format("(%ss)", timeout))
		else
			timeTextDel:setString(string.format("(%ss)", timeout))
		end
	end
    timeout = timeout - 1
    timeTextOk:performWithDelay(handler(self, self._refreshTime), 1)
end

return ClassRef